<template>
  <div>
    <slot />
    <el-dialog
      v-el-drag-dialog 
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      append-to-body
      title="组合查询"
      class="lnk-combinefilter"
      :visible.sync="visible"
      @close="onCancel"
    >
      <div ref="filterbox" class="filterbox">
        <el-row ref="formbox" class="formbox">
          <div
            v-for="(result,index) in results"
            :key="index"
            class="filter-item"
          >
            <el-form
              :validate-on-rule-change="false"
              :rules="getRules(result,index)"
              :model="result"
            >
              <!--选字段-->
              <el-form-item prop="field">
                <el-select
                  v-model="result.field"
                  clearable
                  :multiple="result.multi"
                  :popper-append-to-body="false"
                  size="mini"
                  placeholder="请选择字段…"
                  @change="onFieldChange(index)"
                >
                  <el-option
                    v-for="(filter,lIndex) in filters"
                    :key="filter.id || lIndex"
                    :label="filter.name"
                    :value="filter.field"
                  />
                </el-select>
              </el-form-item>

              <!--选条件-->
              <el-form-item prop="condition">
                <el-select
                  v-model="result.condition"
                  clearable
                  :popper-append-to-body="false"
                  placeholder="请选择条件…"
                  size="mini"
                  @change="conditionChangeHandle(index)"
                >
                  <el-option
                    v-for="(condition,mIndex) in getCondtions(result)"
                    :key="condition.id || mIndex"
                    :label="condition.name"
                    :value="condition.val"
                  />
                </el-select>
              </el-form-item>

              <!--选筛选值-->
              <el-form-item v-show="isNoValue(result)">
                <el-input
                  :disabled="true"
                  size="mini"
                  placeholder="请输入筛选值…"
                />
              </el-form-item>
              <el-form-item
                v-show="!isNoValue(result) && isMultiValue(result) && !isMultiText(result)"
                prop="values"
              >
                <el-select
                  v-if="result.type==='select'"
                  v-model="result.values"
                  clearable
                  placeholder="请选择筛选值…"
                  :multiple="true"
                  :popper-append-to-body="false"
                  class="value-select"
                  size="mini"
                  @change="validateRow(index)"
                >
                  <el-option
                    v-for="(option,rIndex) in getFilterOptions(result)"
                    :key="option.dictId || rIndex"
                    :label="option.dictName"
                    :value="option.dictCode"
                  />
                </el-select>
                <el-date-picker
                  v-else-if="result.type==='date'"
                  v-model="result.values"
                  placeholder="请选择日期范围…"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  size="mini"
                  @change="validateRow(index)"
                />
                <el-date-picker
                  v-else-if="result.type==='datetime'"
                  v-model="result.values"
                  placeholder="请选择时间范围…"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange"
                  size="mini"
                  @change="validateRow(index)"
                />
                <!-- <link-picklist
                  v-else-if="result.type==='picklist' && result.isLink"
                  v-model="result.values"
                  v-bind="result.pickProps"
                  placeholder="请选择筛选值…"
                  :multi="true"
                  @change="validateRow(index)"
                />
                <lnk-picklist
                  v-else-if="result.type==='picklist'"
                  v-model="result.values"
                  picklist-type="input"
                  placeholder="请选择筛选值…"
                  v-bind="result.pickProps"
                  :multi="true"
                  @change="validateRow(index)"
                /> -->
                <div
                  v-else-if="result.type==='number' && result.condition==='between'"
                  class="el-date-editor el-range-editor el-input__inner el-date-editor--daterange el-range-editor--mini"
                >
                  <input
                    v-model="result.start"
                    class="el-range-input"
                    @input="setNumBetween(index,result)"
                  >
                  <span class="el-range-separator">-</span>
                  <input
                    v-model="result.end"
                    class="el-range-input"
                    @input="setNumBetween(index,result)"
                  >
                </div>
              </el-form-item>
              <el-form-item
                v-show="!isNoValue(result) && isMultiValue(result) && isMultiText(result)"
                prop="value"
              >
                <el-input
                  v-model.trim="result.value"
                  size="mini"
                  placeholder="请输入筛选值…"
                  @change="validateRow(index, $event, result)"
                />
              </el-form-item>
              <el-form-item
                v-show="!isNoValue(result) && !isMultiValue(result)"
                prop="value"
              >
                <el-select
                  v-if="result.type==='select'"
                  v-model="result.value"
                  placeholder="请选择筛选值…"
                  :popper-append-to-body="false"
                  class="value-select"
                  size="mini"
                  @change="validateRow(index)"
                >
                  <el-option
                    v-for="(option,rIndex) in getFilterOptions(result)"
                    :key="option.dictId || rIndex"
                    :label="option.dictName"
                    :value="option.dictCode"
                    @change="validateRow(index)"
                  />
                </el-select>                
                <el-date-picker
                  v-else-if="['date','datetime'].includes(result.type) &&  result.condition==='today'"
                  v-model="result.value"
                  placeholder="请选择日期"
                  value-format="yyyy-MM-dd"
                  type="date"
                  size="mini"
                  disabled
                  @change="validateRow(index)"
                />
                <el-date-picker
                  v-else-if="result.type==='date'"
                  v-model="result.value"
                  placeholder="请选择日期…"
                  value-format="yyyy-MM-dd"
                  size="mini"
                  @change="validateRow(index)"
                />
                <el-date-picker
                  v-else-if="result.type==='datetime'"
                  v-model="result.value"
                  type="datetime"
                  placeholder="请选择日期时间…"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  size="mini"
                  @change="validateRow(index)"
                />
                <!-- <link-picklist
                  v-else-if="result.type==='picklist' && result.isLink"
                  v-model="result.value"
                  v-bind="result.pickProps"
                  :selected.sync="result.pickval"
                  placeholder="请选择筛选值…"
                  @change="validateRow(index)"
                />
                <lnk-picklist
                  v-else-if="result.type==='picklist'"
                  v-model="result.value"
                  v-bind="result.pickProps"
                  picklist-type="input"
                  :selected.sync="result.pickval"
                  placeholder="请选择筛选值…"
                  @change="validateRow(index)"
                /> -->
                <el-input
                  v-else
                  v-model.trim="result.value"
                  size="mini"
                  placeholder="请输入筛选值…"
                  @change="validateRow(index)"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  style="float: none"
                  type="text"
                  class="filter-item-del"
                  icon="el-icon-error"
                  @click="removeFilterItem(index)"
                />
              </el-form-item>
            </el-form>
          </div>
        </el-row>
      </div>
      <div class="filterbox_footer">
        <el-button class="clear" @click="clearFilterItem">清空</el-button>
        <el-button class="add blue" @click="addFilterItem"><i class="el-icon-plus" />&nbsp;单字段筛选</el-button>
        <el-button class="add blue" @click="addFilterItem(true)"><i class="el-icon-plus" />&nbsp;多字段筛选</el-button>
      </div>
      <div slot="footer" class="button-footer-box">
        <el-button class="light" @click="onCancel">取消</el-button>
        <el-button class="blue" @click="showSearch(true)">选择查询</el-button>
        <el-button class="blue" @click="showSave">另存为</el-button>
        <el-button class="blue" @click="onConfirm">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="保存"
      append-to-body
      :visible.sync="saveShow"
      class="lnk-combinefilter save"
      :close-on-press-escape="false"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form ref="saveform" :model="saveModel" @submit.native.prevent>
        <el-form-item
          :rules="[{ required: true, message: ' ', trigger: 'blur'}]"
          label="描述"
          prop="filterDescribe"
        >
          <el-input maxlength="10" v-model.trim="saveModel.filterDescribe" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button class="light" :disabled="isSaving" @click="cancelSave">取消</el-button>
        <el-button class="blue" :loading="isSaving" @click="saveSubmit">确定</el-button>
      </span>
    </el-dialog>
    <!-- <lnk-picklist
      class="lnk-combinefilter selector"
      fresh-onshow
      :show.sync="selectShow"
      :grid-options="selectConf"
      @change="onSelect"
    /> -->
    <!-- 选择查询弹出层 -->
    <choose-search :show.sync="showChooseSearch" :tab-index="tabIndex" @chooseSdata="getChooseSearchData" />
    <!-- 选择查询弹出层  @chooseSdata="getChooseSearchData"-->
  </div>
</template>

<script>

import Vue from 'vue'
import axios from 'axios'
import { getResults, deepClone, isMultiText, isNoValue, makeFiltersRaw ,parseTime} from './utils'
import ChooseSearch from '../chooseSearch.vue'
import drag from '../../../directives/el-drag-dialog/drag'

import Emitter from '../util/emitter'
/* 安装消息处理函数*/
Vue.use(Emitter)

export default {
  name: 'LnkCombinefilter',
  components: { ChooseSearch },
  model: {
    prop: 'modelval',
    event: 'change'
  },
  directives:{
    'el-drag-dialog':drag
  },
  props: {
    modelval: {
      type: Array,
      default() {
        return []
      }
    },
    /*表格索引*/
    tabIndex:{
      type:[String,Number],
      default:0
    },

    /* 配置数列*/
    options: {
      type: Array,
      default() {
        return []
      }
    },

    /* 远程配置链接*/
    remote: {
      type: String,
      default: ''
    },

    /* 弹框的显示*/
    show: {
      type: Boolean,
      default() {
        return false
      }
    },

    /* 接口路径*/
    interfacePath: {
      type: String,
      default: ''
    }

  },
  data() {
    return {

      /* 查询条件*/
      conditions: {
        /* 一般字段*/
        normal: [
          { name: '模糊查询', val: 'like' },
          { name: '等于', val: '=' },
          { name: '包含', val: 'in' },
          { name: '排除', val: 'not in' },
          { name: '为空查询', val: 'IS NULL' },
          { name: '非空查询', val: 'NOT NULL' }
        ],
        /* 数字*/
        number: [
          { name: '大于', val: '>' },
          { name: '大于等于', val: '>=' },
          { name: '等于', val: '=' },
          { name: '小于等于', val: '<=' },
          { name: '小于', val: '<' },
          { name: '不等于', val: '<>' },
          { name: '范围查询', val: 'between' },
          { name: '包含', val: 'in' },
          { name: '排除', val: 'not in' },
          { name: '模糊查询', val: 'like' },
          { name: '为空查询', val: 'IS NULL' },
          { name: '非空查询', val: 'NOT NULL' }
        ],
        /* 可选项*/
        select: [
          { name: '等于', val: '=' },
          { name: '包含', val: 'in' },
          { name: '排除', val: 'not in' },
          { name: '为空查询', val: 'IS NULL' },
          { name: '非空查询', val: 'NOT NULL' }
        ],
        /* 日期*/
        date: [
          { name: '晚于', val: '>=' },
          { name: '早于', val: '<=' },
          { name: '当天', val: 'today' },
          { name: '范围查询', val: 'between' },
          { name: '模糊查询', val: 'like' },
          { name: '为空查询', val: 'IS NULL' },
          { name: '非空查询', val: 'NOT NULL' }
        ],
        /* 日期时间*/
        datetime: [
          { name: '晚于', val: '>=' },
          { name: '早于', val: '<=' },
          { name: '当天', val: 'today' },
          { name: '范围查询', val: 'between' },
          { name: '模糊查询', val: 'like' },
          { name: '为空查询', val: 'IS NULL' },
          { name: '非空查询', val: 'NOT NULL' }
        ],
        /* picklist */
        picklist: [
          { name: '等于', val: '=' },
          { name: '包含', val: 'in' },
          { name: '排除', val: 'not in' },
          { name: '为空查询', val: 'IS NULL' },
          { name: '非空查询', val: 'NOT NULL' }
        ],
        /* 多字段单值*/
        multi: [{ name: '模糊匹配', val: 'or like' }]

      },

      /* 接受条件变化的父组件名称*/
      parentName: null,

      /* 弹框的显示*/
      visible: this.show,

      /* 字段信息*/
      filters: [],

      /* 筛选条件*/
      results: [],

      /* 接口路径*/
      interfacePaths: [this.interfacePath],

      /* 保存条件的model*/
      saveModel: {},

      /* 保存弹框的显示*/
      saveShow: false,

      /* 是否正在保存*/
      isSaving: false,

      /* 选择查询弹框的显示*/
      selectShow: false,

      /* 选择查询弹框的Vue实例*/
      selectorDlg: {},

      /* 防止多次点击确定触发多次查询事件*/
      isConfirming: false,

      /* 是否已初始化 */
      isInited: false,
      /* 选择查询框显示与隐藏 */
      showChooseSearch: false
    }
  },
  computed: {
    selectConf() {
      return {
        title: '选择查询条件',
        url: '/',
        fields: [
          { field: 'filterDescribe', name: '描述', minWidth: 120 },
          { field: 'created', name: '创建时间', width: 160 },
          { field: 'filterValue', name: '筛选值', hide: true }
        ],
        params: {
          totalFlag: true,
          interfacePath: this.getInterfacePath(),
          pagePath: location.pathname
        }
      }
    }
  },
  watch: {
    show: {
      immediate: true,
      handler: function(val) {
        this.visible = Boolean(val)
        if (this.visible) {
          this.onShow()
        }
      }
    },
    options: {
      immediate: true,
      handler: function(val) {
        if (this.isInited && Array.isArray(val)) {
          this.initOptions(val)
        }
      }
    }
  },
  created() {
    this.$on('setFilterOptions', (arr) => {
      this.initOptions(arr)
    })
    this.$on('setParentName', (val) => {
      if (val && typeof val === 'string') {
        this.parentName = val
      }
    })
    this.$on('setQueryUrl', (val) => {
      if (val && typeof val === 'string') {
        this.queryurl = val
      }
    })

    this.$on('openDialog', () => {
      if (this.visible) return
      this.visible = true
      this.onShow()
    })

    this.$on('closeDialog', () => {
      if (!this.visible) return
      this.closeDialog()
    })

    if (
      this.remote &&
            typeof this.remote === 'string'
    ) {
      this.fetchRemote(this.remote)
    } else {
      this.initOptions(this.options)
    }
  },
  mounted() {
    // var showButton = this.$getChildComponent('ElButton') || {}
    // if (showButton._isVue) {
    //   showButton.$on('click', () => {
    //     this.visible = !this.visible
    //     if (!this.visible) return
    //     this.visible = true
    //     this.onShow()
    //   })
    // }
  },
  methods: {

    /**
     * @method：initOptions
     * @param：
     * arr：配置信息
     * @description：初始化筛选字段
     */
    initOptions(arr) {
      var filters = []

      if (Array.isArray(arr)) {
        for (var i in arr) {
          var item = arr[i]
          var options = []

          /* 自定义筛选项*/
          if (Array.isArray(item.custom)) {
            try {
              options = deepClone(item.custom)
            } catch (e) {
              console.log(e)
            }

            /* 值列表筛选项*/
          } else if (item.lov && typeof item.lov === 'string') {
            try {
              // options = item.parentLov && item.parentLovVal
              //   ? linkLov.getSubLovArray(item.parentLov, item.parentLovVal, item.lov)
              //   : linkLov.getLovArray(item.lov)
            } catch (e) {
              console.log(e)
            }
          }
          if (options && options.length) {
            filters.push({
              name: item.name,
              type: 'select',
              field: item.field,
              options: options
            })
          } else {
            var type = item.type || item.lnkType || 'normal'
            var tmp = {
              name: item.name,
              type: type,
              field: item.field,
              options: options
            }
            // if (type === 'picklist') {
            //   tmp.pickProps = item.pickProps
            //   tmp.relateField = item.relateField
            //   tmp.isLink = item.isLink
            // }
            filters.push(tmp)
          }
        }
      }
      this.filters = filters
      this.results = []
      this.addFilterItem()
    },

    /**
         * @method：addFilterItem
         * @param：
         * isMulti：是否多字段
         * @description：添加筛选项
         */
    addFilterItem(isMulti) {
      isMulti = typeof isMulti === 'boolean' && isMulti

      var obj = {
        multi: isMulti,
        type: isMulti ? 'multi' : 'normal',
        condition: null,
        field: isMulti ? [] : null,
        value: '',
        values: []
      }
      this.results.splice(
        this.results.length,
        0,
        obj
      )
      this.$nextTick((res) => {
        var ref = this.$refs.filterbox
        ref && ref.scrollTo && ref.scrollTo(0, ref.scrollHeight - ref.clientHeight)
      })
    },
    /**
         * @method：onFieldChange
         * @param：
         * index：筛选项的索引
         * @description：筛选项字段变化时的操作
         */
    onFieldChange(index) {
      if (typeof index !== 'number') return
      var result = this.results[index]
      if (!result.multi) {
        result.value = ''
        result.values = []
        var valid = false
        var arr = this.getCondtions(result) || []
        for (var i in arr) {
          var option = arr[i]
          if (option.val && option.val === result.condition) {
            valid = true
            break
          }
        }
        !valid && (result.condition = null)
      }
      this.conditionChangeHandle(index)
      this.validateRow(index)
    },

    /**
         * @method：setNumBetween
         * @createdBy：HuangJian
         * @params：
         * rowIndex：行索引
         * result:这一行的数据
         * @description：响应数字范围的变化
         *
         */
    setNumBetween(rowIndex, result) {
      if (
        result.start && !isNaN(result.start) &&
                result.end && !isNaN(result.end) &&
                parseFloat(result.start) <= parseFloat(result.end)
      ) {
        result.values = [result.start, result.end]
      } else {
        result.values = []
      }
      this.validateRow(rowIndex)
    },
    conditionChangeHandle(index){
      this.validateRow(index)
      const obj = this.results[index]
      let defVal = new Date()
      if(['date','datetime'].includes(obj.type) && obj.condition==='today'){
        this.$set(this.results[index],'value',parseTime(defVal,'{y}-{m}-{d}'))
      }
    },

    /**
         * @method：validateRow
         * @createdBy：HuangJian
         * @params：
         * index：行索引
         * @description：校验行的输入
         *
         */
    validateRow(index, val, result) {
      if (val) {
        this.$set(result, 'value', val.trim().replaceAll('\\s{1,}', ',') || '')
      }
      var box = this.$refs.formbox || {}
      if (box._isVue) {
        var form = (box.$getChildComponent('ElForm', false) || [])[index]
        form && form.validate && form.validate((valid) => 0)
      }
    },

    /**
         * @method：clearFilterItem
         * @param：
         * @description：清空筛选项
         */
    clearFilterItem() {
      this.results = []
    },

    /**
         * @method：removeFilterItem
         * @param：
         * index：筛选项的索引
         * @description：删除筛选项
         */
    removeFilterItem(index) {
      this.results.splice(index, 1)
    },

    /**
         * @method：getRules
         * @createdBy：HuangJian
         * @params：
         * result：当前行数据
         * @description：根据不同的条件获取不同的校验规则
         *
         */
    getRules(result, index) {
      var rules = {
        field: [{ required: true, message: ' ', trigger: ['change', 'blur'] }],
        condition: [{ required: true, message: ' ', trigger: ['change', 'blur'] }]
      }
      if (!this.isNoValue(result)) {
        if (this.isMultiValue(result)) {
          if (result.type === 'number' && result.condition !== 'between') {
            var handler = function(rule, value, callback) {
              var strRaw = typeof value === 'string' && value || ''
              if (!value) {
                callback(new Error(' '))
              }
              strRaw = strRaw.replaceAll('，', ',')
              var tmpArr = strRaw.split(',') || []
              var newValues = []
              var flag = true
              for (var i in tmpArr) {
                if (tmpArr[i]) {
                  newValues.push(tmpArr[i])
                  if (isNaN(tmpArr[i])) {
                    flag = false
                    break
                  }
                }
              }
              if (!flag || !newValues.length) {
                callback(new Error(' '))
              } else callback()
            }
            rules.values = [
              {
                required: true,
                message: ' ',
                trigger: ['change', 'blur'],
                validator: handler
              }
            ]
          } else if (this.isMultiText(result)) {
            // eslint-disable-next-line no-redeclare
            var handler = function(rule, value, callback) {
              var strRaw = typeof value === 'string' && value || ''
              if (!value) {
                callback(new Error(' '))
              }
              strRaw = strRaw.replaceAll('，', ',')
              var tmpArr = strRaw.split(',') || []
              var newValues = []
              for (var i in tmpArr) {
                tmpArr[i] && newValues.push(tmpArr[i])
              }
              if (!newValues.length) {
                callback(new Error(' '))
              } else callback()
            }
            rules.value = [
              {
                required: true,
                message: ' ',
                trigger: ['change', 'blur'],
                validator: handler
              }
            ]
          } else {
            rules.values = [{ required: true, message: ' ', trigger: ['change', 'blur'] }]
          }
        } else {
          if (result.type === 'number') {
            // eslint-disable-next-line no-redeclare
            var handler = function(rule, value, callback) {
              if (value && !isNaN(value)) {
                callback()
              } else {
                callback(new Error(' '))
              }
            }
            rules.value = [
              {
                required: true,
                message: ' ',
                trigger: ['change', 'blur'],
                validator: handler
              }
            ]
          } else {
            rules.value = [{ required: true, message: ' ', trigger: ['change', 'blur'] }]
          }
        }
      }
      return rules
    },

    /**
         * @method：getCondtions
         * @param：
         * index：筛选项的索引
         * @description：获取筛选项可用的筛选条件
         */
    getCondtions(result) {
      if (typeof result !== 'object') return
      var filterItem = null
      var type = result.type

      if (!result.multi) {
        for (var i in this.filters) {
          if (this.filters[i].field === result.field) {
            filterItem = this.filters[i]
            break
          }
        }
      }
      if (filterItem) {
        type = filterItem.type
        // if (type === 'picklist') {
        //   result.pickProps = filterItem.pickProps
        //   result.relateField = filterItem.relateField
        //   result.isLink = filterItem.isLink
        // }
      }

      var rslt = null
      try {
        rslt = this.conditions[type]
      } catch (e) {
        console.log(e)
      }
      result.type = type
      return rslt || this.conditions.normal
    },

    /**
         * @method：getFilterOptions
         * @param：
         * result：筛选项的值
         * @description：获取筛选项可选值
         */
    getFilterOptions(result) {
      if (typeof result !== 'object') return
      var filterItem = null

      if (!result.multi) {
        for (var i in this.options) {
          if (this.options[i].field === result.field) {
            filterItem = this.options[i]
            break
          }
        }
      }
      var rslt = null
      if (filterItem) {
        rslt = filterItem.options
      }
      return rslt || []
    },

    /**
         * @method：isMultiValue
         * @param：
         * result：筛选项的值
         * @description：是否为单字段多值类型
         */
    isMultiValue(result) {
      if (typeof result !== 'object') return
      var rslt =
                result.condition === 'in' ||
                result.condition === 'not in' ||
                result.condition === 'between'
      result.multival = rslt
      return rslt
    },

    /**
         * @method：isMultiText
         * @createdBy:HuangJian
         * @date:2018/12/4
         * @params：
         * @description：判断是否为用 ，隔开的多值字段
         */
    isMultiText(result) {
      return isMultiText(result)
    },

    /**
         * @method：isNoValue
         * @param：
         * index：筛选项的索引
         * @description：是否要需要筛选值
         */
    isNoValue(result) {
      return isNoValue(result)
    },

    /**
         * @method：checkValid
         * @createdBy：HuangJian
         * @params：
         * @description：检查数据是否符合条件
         *
         */
    checkValid() {
      var unpass = 0
      var box = this.$refs.formbox || {}
      var formList = []
      if (box._isVue) {
        formList = box.$getChildComponent('ElForm', false) || []
      }
      formList.forEach((form) => {
        form.validate && form.validate((valid) => {
          unpass += !valid && 1 || 0
        })
      })
      return unpass === 0
    },

    /**
         * @method：clearCheck
         * @createdBy：HuangJian
         * @params：
         * @description：清楚校验状态
         *
         */
    clearCheck() {
      var box = this.$refs.formbox || {}
      if (box._isVue) {
        var formList = box.$getChildComponent('ElForm', false) || []
        formList.forEach((form) => {
          form.clearValidate && form.clearValidate()
        })
      }
    },

    /**
         * @method：closeDialog
         * @createdBy：HuangJian
         * @params：
         * @description：关闭对话框
         *
         */
    closeDialog() {
      this.selectShow = false
      this.savaShow = false
      this.$nextTick(() => {
        this.visible = false
        this.$emit('update:show', false)
      })
    },

    /**
         * @method：onConfirm
         * @createdBy：HuangJian
         * @params：
         * @description：点击确定
         */
    onConfirm() {
      if (this.isConfirming) return
      this.isConfirming = true
      /* if (!this.results.length) {
        this.$message({ type: 'warning', message: '请先添加筛选条件！', center: true })
        this.isConfirming = false
        return
      } */
      if (!this.checkValid()) {
        this.$message({ type: 'error', message: '还有筛选条件没有填写完整！', center: true })
        this.isConfirming = false
        return
      }
      var filtersraw = this.getFilterRaw() || []
      this.$emit('change', { filtersraw: filtersraw, results: this.results })
      if (this.parentName) {
        this.$dispatch(this.parentName, 'combfilter-change', filtersraw)
      }
      this.closeDialog()
    },

    /**
         * @method：onSelect
         * @createdBy：HuangJian
         * @params：
         * @description：选择查询条件
         *
         */
    onSelect(val) {
      if (val && val.resultsRaw) {
        var results = null
        var filtersRaw = []
        try {
          results = JSON.parse(val.resultsRaw)
          filtersRaw = JSON.parse(val.filterValue)
        } catch (e) {
          console.log(e)
        }
        this.results = []
        this.$nextTick(() => {
          this.results = results || []
          this.$nextTick(() => {
            this.$emit('change', filtersRaw)
            if (this.parentName) {
              this.$dispatch(this.parentName, 'combfilter-change', filtersRaw)
            }
            this.closeDialog()
          })
        })
      }
    },

    /**
         * @method：onCancel
         * @createdBy：HuangJian
         * @params：
         * @description：取消查询
         *
         */
    onCancel() {
      this.closeDialog()
    },

    /**
         * @method：
         * @createdBy：HuangJian
         * @date：2018/11/5
         * @params：
         * @description：打开弹出框时触发
         *
         */

    onShow() {
      this.results = []
      this.selectShow = false
      this.savaShow = false
      this.isConfirming = false
      if (!this.results.length) {
        this.addFilterItem()
      }
      this.$nextTick(() => {
        this.clearCheck()
        this.initOptions(this.options)
        if(this.modelval.length > 0){
          this.results = this.modelval
        }
      })
    },

    /**
         * @method：getFilterRaw
         * @param：
         * @createdBy：HuangJian
         * @description：生成后台可用的filterRaw并返回
         */
    getFilterRaw() {
      return makeFiltersRaw(this.filters, this.results) || []
    },
    /**
         * @method：checkInterFaceValid
         * @createdBy：HuangJian
         * @params：
         * @description：检查是否配置了接口路径
         *
         */
    checkInterFaceValid() {
      var value = true
      if (!this.getInterfacePath()) {
        this.$message({ type: 'error', message: '未指定接口路径！', center: true })
        value = false
      }
      return value
    },
    /**
         * @method：showSelect
         * @createdBy：HuangJian
         * @params：
         * @description：打开选择查询
         *
         */
    showSelect() {
      if (!this.checkInterFaceValid()) {
        return
      }
      this.selectShow = true
    },
    /**
         * @method：getInterfacePath
         * @createdBy:HuangJian
         * @date:2019/1/18
         * @params：
         * @description：获取查询的接口路径
         */
    getInterfacePath() {
      const url = this.queryurl || this.interfacePaths[1] || this.interfacePaths[0]
      return (url || '').replaceAll(url, '') || '/userQueryCondition'
    },
    /**
         * @method：showSave
         * @createdBy：HuangJian
         * @params：
         * @description：打开保存编辑框
         *
         */
    showSave() {
      if (!this.checkInterFaceValid()) {
        return
      }
      if (!this.results.length) {
        this.$message({ type: 'warning', message: '请先添加筛选条件！', center: true })
        return
      }
      if (!this.checkValid()) {
        this.$message({ type: 'error', message: '还有筛选条件没有填写完整！', center: true })
        return
      }
      var results = getResults(this.results) || []
      results.forEach((result) => {
        delete result.multival
        delete result.pickProps
      })
      this.saveModel = {
        interfacePath: this.getInterfacePath(),
        pagePath: location.pathname,
        filterValue: JSON.stringify(this.getFilterRaw() || []),
        resultsRaw: JSON.stringify(results),
        menuCode: this.$route.query.menuCode,
        publicFlag: '1',
        tabIndex:this.tabIndex || 0
      }
      this.saveShow = true
    },

    /**
         * @method：cancelSave
         * @createdBy：HuangJian
         * @params：
         * @description：取消保存
         *
         */
    cancelSave() {
      if (!this.saveShow) return
      var saveform = this.$refs.saveform || {}
      saveform.clearValidate && saveform.clearValidate()
      this.saveShow = false
    },
    /**
         * @method：saveSubmit
         * @createdBy：HuangJian
         * @params：
         * @description：保存到后台
         *
         */
    saveSubmit() {
      if (this.isSaving) return
      this.isSaving = true
      var saveform = this.$refs.saveform || {}
      var valid = false
      saveform.validate && saveform.validate((val) => {
        valid = val
      })
      if (!valid) {
        this.$message({ type: 'error', message: '请先填写描述！', center: true })
        this.isSaving = false
        return
      }
      saveform.clearValidate && saveform.clearValidate()
      var url = '/ucenter/api/v2/userQueryCondition'
      var data = this.saveModel

      axios.post(url, data).then((res) => {

        if (res.success === 1) {
          this.$message({ type: 'success', message: '已保存！可在‘选择查询’中查看', center: true })
          this.$emit('save', res.msg)
          this.saveShow = false
          this.clearCheck()
        } else {
          this.$message({ type: 'error', message: res.msg || '未知错误！', center: true })
        }
        this.isSaving = false
      }).catch((err) => {
        if (!err.response) {
          this.$message({ type: 'error', message: '请检查与服务器的连接！', center: true })
        } else {
          this.$message({ type: 'error', message: err, center: true })
        }
      })
    },

    /**
         * @method：fetchRemote
         * @createdBy：HuangJian
         * @params：
         * url：远程配置路劲
         * @description：获取远程配置信息
         *
         */
    fetchRemote(url) {
      axios.post(url).then((res) => {
        var errorMsg = '加载远程配置失败'
        var data = res.data
        if (
          data && typeof data === 'object' && Array.isArray(data.options)
        ) {
          if (data.interfacePath) {
            this.interfacePaths[1] = data.interfacePath
          }
          this.initOptions(data.options)
        } else if (
          data && typeof data === 'string'
        ) {
          try {
            var obj = JSON.parse(data)
            if (
              obj && obj.options && Array.isArray(obj.options)
            ) {
              if (obj.interfacePath) {
                this.interfacePaths[1] = obj.interfacePath
              }
              this.initOptions(obj.options)
            }
          } catch (e) {
            this.$message({ type: 'error', message: errorMsg, center: true })
          }
        } else {
          this.$message({ type: 'error', message: errorMsg, center: true })
        }
      }).catch((err) => {
        if (!err.response) {
          this.$message({ type: 'error', message: '请检查与服务器的连接！', center: true })
          return
        }
        if (err.response && err.response.status === 404) {
          this.$message({ type: 'error', message: '远程配置信息不存在！', center: true })
        }
      })
    },
    // 显示隐藏选择查询
    showSearch(val) {
      this.showChooseSearch = val
    },
    // 获取选择查询数据
    getChooseSearchData(data) {
      const nowDate =  parseTime(new Date(),'{y}-{m}-{d}')
      const filterValue = JSON.parse(data.filterValue)
      filterValue.forEach(v=>{
        if(v.operator==='today'){
          // 处理条件为当天的数据
          v.value = nowDate
        }
      })

      const resultsRaw = JSON.parse(data.resultsRaw)
      resultsRaw.forEach(v=>{
        if(v.condition==='today'){
          // 处理条件为当天的数据
          v.value = nowDate
        }
      })
      
      this.$emit('change', 
        { 
          filtersraw: filterValue, 
          results:  resultsRaw
        }
      )
      this.closeDialog()
    }

  }
}
</script>
